package com.cjb.cloudimages.api;

import com.cjb.common.exception.ServerException;
import com.cjb.common.util.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class imageApi
 * @Date 2023-11-04 下午11:03
 */
//@RestController
    @Service
//@RequestMapping("images")
public class ImageApi {

    private static final Logger log = LoggerFactory.getLogger(ImageApi.class);

    /**
     * 注入服务API的URL
     */
    @Value("${images.url}")
    public String imageUrl;
    /**
     * python图形加密Api
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    //@GetMapping("embed")
    public HttpEntity<byte[]> embedImage(MultipartFile imgOri , MultipartFile imgWm)   {
        log.info("打印是否为空值1 {}", Common.isEmpty(imgOri));
        log.info("打印是否为空值2 {}", Common.isEmpty(imgWm));

        //创建一个RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        //设置数据头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

//        log.info("打印传入的数据 {}", JsonUtils.toJsonString(imgOri));
//        log.info("打印传入的数据 {}",JsonUtils.toJsonString(imgWm));
        LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        try {
            if (Common.isNotEmpty(imgOri)){
                body.add("img_ori",new ByteArrayResource(imgOri.getBytes()){
                    @Override
                    public String getFilename() {
                        return imgOri.getOriginalFilename();
                    }
                    @Override
                    public long contentLength() {
                        return imgOri.getSize();
                    }
                });
            }
            if (Common.isNotEmpty(imgWm)){
                body.add("img_wm", new ByteArrayResource(imgWm.getBytes()){
                    @Override
                    public String getFilename() {
                        return imgWm.getOriginalFilename();
                    }
                    @Override
                    public long contentLength() {
                        return imgWm.getSize();
                    }
                });
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        log.info("打印地址 {}",imageUrl+"polls/embed/");
        byte[] response = restTemplate.exchange(
                imageUrl + "polls/embed/",
                HttpMethod.POST,
                httpEntity,
                byte[].class
        ).getBody();
        return  Common.isNotEmpty(response)?getEntityWithContentDispositionHeader(response, "out.png"):null;
    }

    /**
     * 图片解码
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    //@GetMapping("extract")
    public HttpEntity<byte[]> extractImage(MultipartFile imgFile)   {
        //创建一个RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        //设置数据头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        try {
            body.add("img_file",new ByteArrayResource(imgFile.getBytes()){
                @Override
                public String getFilename() {
                    return imgFile.getOriginalFilename();
                }
                @Override
                public long contentLength() {
                    return imgFile.getSize();
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        log.info("打印地址 {}",imageUrl+"polls/extract/");
        byte[] response = restTemplate.exchange(
                imageUrl+"polls/extract/",
                HttpMethod.POST,
                httpEntity,
                byte[].class
        ).getBody();

        return getEntityWithContentDispositionHeader(response, "out.png");
    }

    /**
     * 图片相似度校验
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    //@GetMapping("similarity")
    public String similarityImage(MultipartFile img1File,MultipartFile img2File)   {
        if (Common.isEmpty(img1File)){
             throw new ServerException("img1File 是空的");
        }
        if (Common.isEmpty(img2File)){
            throw new ServerException("img2File 是空的");
        }
        //创建一个RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        //设置数据头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        try {
            body.add("img_ori",new ByteArrayResource(img1File.getBytes()){
                @Override
                public String getFilename() {
                    return img1File.getOriginalFilename();
                }
                @Override
                public long contentLength() {
                    return img1File.getSize();
                }
            });
            body.add("img_wm",new ByteArrayResource(img2File.getBytes()){
                @Override
                public String getFilename() {
                    return img2File.getOriginalFilename();
                }
                @Override
                public long contentLength() {
                    return img2File.getSize();
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(body, headers);
        log.info("打印地址 {}",imageUrl+"polls/similarity");
        return restTemplate.exchange(
                imageUrl+"polls/similarity",
                HttpMethod.POST,
                httpEntity,
                String.class
        ).getBody();
    }
    private HttpEntity<byte[]> getEntityWithContentDispositionHeader(byte[] imageBytes, String filename) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentDisposition(ContentDisposition.builder("attachment")
                .filename(filename)
                .build());
        return new HttpEntity<>(imageBytes, headers);
    }


}
